package com.fafu.mq.mqserver;

import com.fafu.mq.common.*;
import com.fafu.mq.common.arguments.*;
import com.fafu.mq.common.returns.BasicReturns;
import com.fafu.mq.common.returns.SubScribeReturns;
import com.fafu.mq.mqserver.core.BasicProperties;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BrokerServer {
    private ServerSocket serverSocket = null;

    // 当前考虑一个 BrokerServer 上只有一个虚拟主机
    private VirtualHost virtualHost = new VirtualHost("default");
    // 使用这个 哈希表 表示当前的所有会话 (就是有哪些客户端在和服务器进行通信)
    // 此处的 key 是 channelId
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<>();
    // 引入一个线程池, 来处理多个客户端
    private ExecutorService executorService = null;
    // 引入一个 boolean 变量控制服务器是否继续运行
    private volatile boolean runnable = true;

    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("[BrokerService] 启动! ");
        executorService = Executors.newCachedThreadPool();
         try {
             while (runnable) {
                 Socket clientSocket = serverSocket.accept();
                 // 把处理连接的逻辑丢给这个线程池
                 executorService.submit(() ->{
                     processConnection(clientSocket);
                 });
             }
         } catch (SocketException e) {
             System.out.println("[BrokerServer] 服务器停止运行!");
         }
    }

    // 一般来说停止服务器, 就是直接 kill 掉进程就可以了
    // 此处还是搞了一个可以单独停止的方法, 主要是用于单元测试
    public void stop() throws IOException {
        runnable = false;
        // 线程池的任务放弃, 销毁线程
        executorService.shutdownNow();
        serverSocket.close();
    }


    // 通过这个方法, 来处理一个客户端的连接
    // 在这个连接中, 可能会涉及多个请求和响应
    private void processConnection(Socket clientSocket) {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            // 这里需要按照特定的格式来进行读取, 需要用到之前的 DataInputStream 和 DataOutputStream
            try (DataInputStream dataInputStream = new DataInputStream(inputStream);
                 DataOutputStream dataOutputStream = new DataOutputStream(outputStream)){
                while (true) {
                    // 1. 读取请求并解析
                    Request request = readRequest(dataInputStream);
                    // 2. 根据请求计算响应
                    Response response = process(request,clientSocket);
                    // 3. 把响应写回客户端
                    writeResponse(dataOutputStream,response);
                }
            }
        } catch (EOFException  | SocketException e) {
            // 对于这个代码来说, DataInputStream 如果读到了 EOF , 就会抛出异常
            // 借助这个异常来结束循环
            System.out.println("[BrokerService] 连接关闭! 客户端地址: " + clientSocket.getInetAddress().toString() +
                    ":" + clientSocket.getPort());
        } catch (IOException | ClassNotFoundException | MqException e) {
            System.out.println("[BrokerService] 服务器连接出现异常! ");
        } finally {
            try {
                // 当连接处理完了, 就需要关闭 socket
                clientSocket.close();
                // 一个 TCP 连接中, 可能包含多个 channel. 需要把当前这个 socket 的所有 channel 也要顺便都清理掉
                clearClosedSession(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }




    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        request.setType(dataInputStream.readInt());
        request.setLength(dataInputStream.readInt());
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if (n != request.getLength()) {
            throw new IOException("读取请求的格式出错");
        }
        request.setPayload(payload);
        return request;
    }


    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        // 这个刷新缓冲区也是重要的操作, 快速刷进去!!
        dataOutputStream.flush();
    }
    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException, MqException {
        // 1. 把 payload 做一个初步的解析
        BasicArguments basicArguments = (BasicArguments) BinaryTool.fromBytes(request.getPayload());
        System.out.println("[Request] rid = " + basicArguments.getRid() +
                ", channelId = " + basicArguments.getChannelId());
        // 2. 根据 type 的值, 来进一步去区分接下来的请求要干什么
        int type = request.getType();
        boolean ok = true;
        if (type == 0x1) {
            // 创建 channel
            sessions.put(basicArguments.getChannelId(), clientSocket);
            System.out.println("[BrokerServer] 创建 channel 完成! channelId = " + basicArguments.getChannelId());
        } else if (type == 0x2) {
            // 销毁 channel
            sessions.remove(basicArguments.getChannelId());
            System.out.println("[BrokerServer] 销毁 channel 完成! channelId = " + basicArguments.getChannelId());
        } else if (type == 0x3) {
            // 创建交换机
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(), arguments.getExchangeType(), arguments.isDurable(),
                    arguments.isAutoDelete(), arguments.getArguments());
        } else if (type == 0x4) {
            // 销毁交换机
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) basicArguments;
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());
        } else if (type == 0x5) {
            // 创建队列
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDeclare(arguments.getQueueName(), arguments.isDurable(), arguments.isExclusive(),
                    arguments.isAutoDelete(), arguments.getArguments());
        } else if (type == 0x6) {
            // 删除队列
            QueueDeleteArguments arguments = (QueueDeleteArguments) basicArguments;
            ok = virtualHost.queueDelete(arguments.getQueueName());
        } else if (type == 0x7) {
            // 创建绑定
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueBind(arguments.getQueueName(), arguments.getExchangeName(), arguments.getBindingKey());
        } else if (type == 0x8) {
            // 删除绑定
            QueueUnbindArguments arguments = (QueueUnbindArguments) basicArguments;
            ok = virtualHost.queueUnBind(arguments.getQueueName(), arguments.getExchangeName());
        } else if (type == 0x9) {
            // 发送消息
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;
            ok = virtualHost.basicPublish(arguments.getExchangeName(), arguments.getRoutingKey(), arguments.getBasicProperties(), arguments.getBody());
        } else if (type == 0xa) {
            // 订阅一个消息
            BasicConsumeArguments arguments = (BasicConsumeArguments) basicArguments;
            ok = virtualHost.basicConsume(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoAck(), new Consumer() {
                // 这个回调函数的主要作用就是, 把服务器收到的消息直接推送给客户端
                @Override
                public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                    // 先知道当前这个收到的消息, 要发给哪个客户端
                    // 此处的 consumerTag 是 channelId. 根据 channelId 查询 可以知道 clientSocket 对象, 往里面发送数据
                    // 1. 根据 channelId 找到 socket 对象
                    Socket clientSocket = sessions.get(consumerTag);
                    if (clientSocket == null || clientSocket.isClosed()) {
                        throw new MqException("[BrokerServer] 订阅消息的客户端已经关闭了!");
                    }
                    // 2. 构造响应数据
                    SubScribeReturns subScribeReturns = new SubScribeReturns();
                    subScribeReturns.setChannelId(consumerTag);
                    subScribeReturns.setBody(body);
                    subScribeReturns.setBasicProperties(basicProperties);
                    subScribeReturns.setConsumerTag(consumerTag);
                    // 由于这里只有响应没有请求, 不需要去对应, rid 暂时不需要
                    subScribeReturns.setRid("");
                    subScribeReturns.setOk(true);
                    byte[] payload = BinaryTool.toBytes(subScribeReturns);
                    Response response = new Response();
                    // 0xc 表示服务器给消费者客户端推送数据
                    response.setType(0xc);
                    // response 的 payLoad 是一个 SubScribeReturns 对象
                    response.setLength(payload.length);
                    response.setPayload(payload);
                    // 3. 把数据写回客户端
                    // 4. 注意! 此处的 dataOutputStream 不能进行 close 操作
                    // 如果把 这个关闭就会把 clientSocket 里的 dataOutputStream 给关闭了
                    // 此处就无法继续写入了
                    DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                    writeResponse(dataOutputStream, response);
                }
            });
        } else if (type == 0xb) {
            // 调用 basicAck 确认消息
            BasicAckArguments arguments = (BasicAckArguments) basicArguments;
            ok = virtualHost.basicAck(arguments.getQueueName(), arguments.getMessageId());

        } else {
            // 当前的 type 是非法的
            throw new MqException("[BrokerServer] 未知的 type! type = " + type);
        }
        // 3. 构造响应
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setChannelId(basicArguments.getChannelId());
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setOk(ok);
        byte[] payload = BinaryTool.toBytes(basicReturns);
        Response response = new Response();
        response.setType(type);
        response.setLength(payload.length);
        response.setPayload(payload);
        System.out.println("[Response] rid = " + basicReturns.getRid() + ", channelId = " + basicReturns.getChannelId() +
                ", type = " + response.getType() + ", length = " + response.getLength());
        return response;
    }


    private void clearClosedSession(Socket clientSocket) {
        // 这里要做的主要是遍历上述的 sessions 哈希表, 把该关闭的 socket 键值对都删除掉
        List<String> todDeleteChannelId = new ArrayList<>();
        for (Map.Entry<String,Socket> entry : sessions.entrySet()) {
            if (entry.getValue() == clientSocket) {
                todDeleteChannelId.add(entry.getKey());
            }
        }

        for (String channelId : todDeleteChannelId) {
            sessions.remove(channelId);
        }
        System.out.println("[BrokerServer] 清理 session 完成! 被清理的 channelId = " + todDeleteChannelId);
    }
}
